<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="产品SKU" prop="sku">
        <el-input v-model="queryParams.sku" placeholder="请输入产品SKU" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库" prop="ordersId">
        <treeselect v-model="queryParams.warehouseId" :options="warehouseOptions" :show-count="true" placeholder="请选择仓库"
          style="width: 210px" />
      </el-form-item>
      <el-form-item label="变动类型" prop="changeType">
        <el-select v-model="queryParams.changeType" placeholder="请选择变动类型" clearable>
          <el-option v-for="dict in dict.type.types_of_inventory_changes" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="变动日期" prop="changeDate">
        <el-date-picker clearable v-model="queryParams.changeDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择变动日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['depot:localInventoryDetails:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['depot:localInventoryDetails:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['depot:localInventoryDetails:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['depot:localInventoryDetails:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="localInventoryDetailsList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="库存变动明细的唯一标识" align="center" prop="inventoryDetailId" /> -->
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品SKU" align="center" prop="sku" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="变动类型" align="center" prop="changeType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.types_of_inventory_changes" :value="scope.row.changeType" />
        </template>
      </el-table-column>
      <el-table-column label="变动差异" align="center" prop="quantity">
        <template slot-scope="scope">
          <span :class="getQuantityCellStyleAndContent(scope.row).styleClass">
            {{ getQuantityCellStyleAndContent(scope.row).displayContent }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="变动前数量" align="center" prop="previousQuantity" />
      <el-table-column label="变动后数量" align="center" prop="postChangeQuantity" />
      <el-table-column label="关联单据" align="center" prop="referenceId" />
      <el-table-column label="变动日期" align="center" prop="changeDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.changeDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="notes" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
import { listLocalInventoryDetails, getLocalInventoryDetails, delLocalInventoryDetails, addLocalInventoryDetails, updateLocalInventoryDetails } from "@/api/depot/localInventoryDetails";
import { getSelectPreWarehouseTreeList } from "@/api/procured/plan";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "LocalInventoryDetails",
  dicts: ['types_of_inventory_changes'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存变动明细表格数据
      localInventoryDetailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        warehouseId: null,
        changeType: null,
        changeDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inventoryDetailId: [
          { required: true, message: "库存变动明细的唯一标识不能为空", trigger: "blur" }
        ],
        inventoryId: [
          { required: true, message: "关联库存表ID不能为空", trigger: "blur" }
        ],
        sku: [
          { required: true, message: "产品SKU不能为空", trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "仓库ID不能为空", trigger: "blur" }
        ],
      },
      // 仓库列表
      warehouseOptions: [],
      // 定义变动数量增加时的样式类名
      increaseStyleClass: 'text-green',
      // 定义变动数量减少时的样式类名
      decreaseStyleClass: 'text-red',
    };
  },
  created() {
    this.getList();
    this.getPreWarehouse();
  },
  computed: {
    getQuantityCellStyleAndContent() {
      return (row) => {
        const diff = row.postChangeQuantity - row.previousQuantity;
        if (diff < 0) {
          return {
            styleClass: this.decreaseStyleClass,
            displayContent: `${diff}`
          };
        } else if (diff > 0) {
          return {
            styleClass: this.increaseStyleClass,
            displayContent: `+${Math.abs(diff)}`
          };
        }
        return {
          styleClass: '',
          displayContent: ''
        };
      };
    }
  },
  methods: {
    /** 查询库存变动明细列表 */
    getList() {
      this.loading = true;
      listLocalInventoryDetails(this.queryParams).then(response => {
        this.localInventoryDetailsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryDetailId: null,
        inventoryId: null,
        sku: null,
        warehouseId: null,
        changeType: null,
        quantity: null,
        changeDate: null,
        referenceId: null,
        notes: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryDetailId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存变动明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inventoryDetailId = row.inventoryDetailId || this.ids
      getLocalInventoryDetails(inventoryDetailId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存变动明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inventoryDetailId != null) {
            updateLocalInventoryDetails(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLocalInventoryDetails(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryDetailIds = row.inventoryDetailId || this.ids;
      this.$modal.confirm('是否确认删除库存变动明细编号为"' + inventoryDetailIds + '"的数据项？').then(function () {
        return delLocalInventoryDetails(inventoryDetailIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('depot/localInventoryDetails/export', {
        ...this.queryParams
      }, `localInventoryDetails_${new Date().getTime()}.xlsx`)
    },
    /** 查询仓库 */
    getPreWarehouse() {
      getSelectPreWarehouseTreeList().then((response) => {
        this.warehouseOptions = response.data;
      });
    },
  }
};
</script>
<style>
.text-green {
  color: green;
}

.text-red {
  color: red;
}
</style>